<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/16 0016
 * Time: 下午 13:51
 */

namespace Home\Controller;
use Think\Controller;

class CommonController extends Controller{
    protected $userid; //当前用户
    protected $corpid;  //企业号ID
    protected $secret;  //企业号secret
    protected $agentid;  //当前应用ID
    protected $token;  //access_token

    public function __construct(){
        parent::__construct();
        //企业号数据区域
        $this -> corpid  = C('CORPID');
        $this -> secret  = C('SECRET');
        $this -> agentid = C('AGENTID');

        //获取access_token
        $this->token = access_token($this->corpid,$this->secret);

        //获取user信息
        /***测试数据开始*/
        //session('userid','WangJun');
        /***测试数据结束*/
        if(!$userid = session('userid')){
            $userid = $this->getUserId();
        }
        $this->userid = $userid;

        //通过config接口注入权限验证配置
        require_once './Org/Chat/jssdk.php';
        $this -> jssdk = new \JSSDK($this -> corpid,$this -> secret);
        $this -> signPackage = $this -> jssdk -> GetSignPackage();

        session('signPackage',$this->signPackage);

    }

    //获取userid
    public function getUserId(){
        //获取userid
        $code = I('get.code');
        if (!$code) {
            $this->error('未经授权用户e1!');
            exit;
        }

        $userid_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$this->token}&code={$code}";
        $res = json_decode(https_request($userid_url), true);
        if (!$userid = $res['UserId']) {
            $this->error('未经授权用户e2!');
        }
        session('userid', $userid);
        return $userid;
    }

    /*
     * 根据userid 获取userid的详细信息
     */
    public function getUserList($userid){
        if($user_info = S($userid.'_user_info')){
            return $user_info;
        }
        //获取userid的详细信息
        $user_info_url_ = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={$this->token}&userid={$userid}";
        $user_info = json_decode(https_request($user_info_url_),true);
        if(!$bumen_id = $user_info['department'][0]){
            $this -> error('获取部门失败1!');
        }
        //dump($user_info);

        //获取userid所在部门名称
        $bumen_url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={$this->token}&id={$bumen_id}";
        $bumen_info = json_decode(https_request($bumen_url),true);

        if(!$bumen_name = $bumen_info['department'][0]['name']){
            $this -> error('获取部门失败2!');
        }
        $user_info = array(
            'user_name' => $user_info['name'],
            'bumen_name' => $bumen_name,
            'mobile' => $user_info['mobile'] ? $user_info['mobile'] : '',
            'user_avatar' => $user_info['avatar'] ? $user_info['avatar'].'64' : '',
        );
        S($userid.'_user_info',$user_info,3600*20);
        return $user_info;
    }


    /**
     * 缓存该企业号下所有成员
     */
    protected function cache_all_user(){
        if($all_user = S($this -> corpid.'_all_user')){
            return $all_user;
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={$this->token}&department_id=1&fetch_child=1&status=1";
        $res = json_decode(https_request($url),true)['userlist'];
        $buffer = array();
        foreach($res as $k => $v){
            $buffer[$v['userid']]['name'] = mb_substr($v['name'],0,3,'utf-8');
            $buffer[$v['userid']]['mobile'] = isset($v['mobile']) ? $v['mobile'] : '';
            $buffer[$v['userid']]['position'] = isset($v['position']) ? $v['position'] : '';
            $buffer[$v['userid']]['gender'] = isset($v['gender']) ? $v['gender'] : '';
            $buffer[$v['userid']]['avatar'] = isset($v['avatar']) ? $v['avatar'].'64' : '';
            $buffer[$v['userid']]['department'] = implode(',',$v['department']);
        }
        //缓存数据
        S($this -> corpid.'_all_user',$buffer,3600*20);
        return $buffer;
    }

    //通过config接口注入权限验证配置
    protected function jsdk_conf(){
        if(!$signPackage = session('signPackage')){
            require_once './Org/Chat/jssdk.php';
            $jssdk = new \JSSDK($this -> corpid,$this -> secret);
            $signPackage = $jssdk -> GetSignPackage();

            session('signPackage',$signPackage);
        }
        //dump($signPackage);exit;

        $this -> assign('signPackage',$signPackage);
    }

    /**
     * 企业号通讯录选择人
     */
    protected function openEnterpriseContact(){
        //获取token
        $token = $this -> token;
        //获取管理组凭证
        $url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token={$token}&type=contact";
        $res = https_request($url);
        $res = json_decode($res,true);
        $group_id = $res['group_id'];
        $ticket = $res['ticket'];
        //生成通讯录签名
        $noncestr = $this -> createNonceStr();
        $timestamp = time();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $string = "group_ticket={$ticket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}";
        $signature = sha1($string);
        $this -> assign([
            'groupId' => $group_id,
            'timestamp' => $timestamp,
            'nonceStr' => $noncestr,
            'signature' => $signature,
        ]);

    }

    /**
     * 生成随机字符串
     */
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

}